<template>
  <a-drawer
    :visible="formVisible"
    :width="500"
    unmount-on-close
    :title="isEdit ? '编辑' : '新增'"
    @ok="submit"
    @cancel="close"
  >
    <div>
      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        :label-col-props="{ span: 8 }"
        :wrapper-col-props="{ span: 16 }"
      >
        <a-form-item field="username" label="用户名" required>
          <a-input v-model="form.username" placeholder="请填写用户名" />
        </a-form-item>
        <a-form-item v-if="!isEdit" field="password" label="密码" required>
          <a-input v-model="form.password" placeholder="请填写密码" />
        </a-form-item>
        <a-form-item field="orgId" label="所属机构" required>
          <a-tree-select
            v-model="form.orgId"
            :field-names="{
              key: 'id',
              title: 'name',
              children: 'children',
            }"
            :data="treeData"
            placeholder="请选择组织机构"
          />
        </a-form-item>
        <a-form-item field="roleIds" label="角色" required>
          <a-checkbox-group v-model="form.roleIds">
            <!-- 角色的id 和 名称 -->
            <a-checkbox v-for="{ roleName, id } in roles" :key="id" :value="id">
              {{ roleName }}
            </a-checkbox>
          </a-checkbox-group>
        </a-form-item>
        <a-form-item field="phone" label="手机号">
          <a-input v-model="form.phone" placeholder="请填写手机号" />
        </a-form-item>
        <a-form-item field="status" label="是否锁定" required>
          <a-radio-group v-model="form.status">
            <a-radio value="1">是</a-radio>
            <a-radio value="0">否</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </div>
  </a-drawer>
</template>

<script lang="ts" setup>
  import { FieldRule, Message } from '@arco-design/web-vue';
  import { ref, reactive, computed } from 'vue';
  import { addUser, updateUser } from '@/api/upms/user';
  import { getOrgTree } from '@/api/upms/org';
  import { getRoleList } from '@/api/upms/role';
  import { useVisible } from '@/hooks/visible';
  import { useRequest } from 'vue-request';

  const formRef = ref();

  const form = ref();

  const initData = reactive({
    id: '',
    username: '',
    password: '',
    orgId: '',
    roleIds: [],
    phone: '',
    userType: 0,
    status: '0',
  });

  const { data: treeData, runAsync: getOrgTreeAsync } = useRequest(getOrgTree, {
    manual: true,
  });

  const { data: roles, runAsync: getRoleListAsync } = useRequest(getRoleList, {
    manual: true,
  });

  const rules: Record<string, FieldRule[]> = {
    username: [
      {
        type: 'string',
        required: true,
        message: '用户名不能为空',
      },
    ],
    password: [
      {
        type: 'string',
        required: true,
        message: '密码不能为空',
      },
      { minLength: 8, message: '密码长度至少为8位' },
    ],
    orgId: [
      {
        type: 'string',
        required: true,
        message: '组织机构不能为空',
      },
    ],
    roleIds: [
      {
        type: 'string',
        required: true,
        message: '角色不能为空',
      },
    ],
    status: [
      {
        type: 'string',
        required: true,
        message: '是否锁定不能为空',
      },
    ],
  };

  const props = defineProps({
    visible: {
      type: Boolean,
      default: false,
    },
    formData: {
      type: Object,
      default: () => {
        return {};
      },
    },
  });

  const emit = defineEmits<{
    (e: 'update:visible', v: boolean): void;
    (e: 'refresh'): void;
  }>();

  const { formVisible, open, close } = useVisible(props, emit);

  // 判断是编辑还是新增
  const isEdit = computed(() => !!form.value?.id);

  const submit = async () => {
    formVisible.value = true;
    const validate = await formRef.value.validate();
    if (!validate) {
      if (isEdit.value) {
        await updateUser(form.value).then(() => {
          Message.success('修改成功');
        });
      } else {
        await addUser(form.value).then(() => {
          Message.success('添加成功');
        });
      }
      form.value = { ...initData };
      formVisible.value = false;
      emit('refresh');
    }
  };

  open(() => {
    const { id } = props.formData;
    form.value = id ? props.formData : initData;
    getOrgTreeAsync();
    getRoleListAsync();
  });
</script>
